package com.yu.service.system;

import java.util.List;

import cn.hutool.core.util.IdUtil;
import com.wf.captcha.ArithmeticCaptcha;
import com.yu.entity.Auth.AuthUserEntity;
import com.yu.entity.Auth.JwtUserEntity;
import com.yu.entity.Auth.TokenEntity;
import com.yu.entity.CaptchaEntity;
import com.yu.entity.system.UserConditionEntity;
import com.yu.entity.system.UserEntity;
import com.yu.exception.BusinessException;
import com.yu.helper.TokenHelper;
import com.yu.mapper.system.UserMapper;
import com.yu.utils.AssertUtil;
import com.yu.utils.PasswordUtil;
import com.yu.utils.RedisUtils;
import com.yu.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import com.yu.entity.ResponsePageEntity;

import javax.servlet.http.HttpServletRequest;

/**
 * 系统用户 服务层
 *
 * @author maxinyu 该代码由maxinyu生成
 * @date 2025-06-02 15:26:06
 */
@Slf4j
@Service
public class UserService {
	private static final String CAPTCHA_PREFIX = "captcha:";
	private static final int CAPTCHA_EXPIRE_SECOND = 120; // 验证码有效期为120秒

	@Autowired
	private UserMapper userMapper;
//	@Qualifier("authenticationManagerBuilder")
//	@Autowired
//	private AuthenticationManagerBuilder authenticationManagerBuilder;

	@Autowired
	private AuthenticationManager authenticationManager;
    @Autowired
    private TokenHelper tokenHelper;
	@Autowired
	private PasswordUtil passwordUtil;
	@Autowired
	private RedisUtils redisUtils;

	/**
     * 查询系统用户信息
     *
     * @param id 系统用户ID
     * @return 系统用户信息
     */
	public UserEntity findById(Long id) {
	    return userMapper.findById(id);
	}

	/**
     * 根据条件分页查询系统用户列表
     *
     * @param userConditionEntity 系统用户信息
     * @return 系统用户集合
     */
	public ResponsePageEntity<UserEntity> searchByPage(UserConditionEntity userConditionEntity) {
		int count = userMapper.searchCount(userConditionEntity);
		if (count == 0) {
			return ResponsePageEntity.buildEmpty(userConditionEntity);
		}
		List<UserEntity> dataList = userMapper.searchByCondition(userConditionEntity);
		return ResponsePageEntity.build(userConditionEntity, count, dataList);
	}

    /**
     * 新增系统用户
     *
     * @param userEntity 系统用户信息
     * @return 结果
     */
	public int insert(UserEntity userEntity) {
	    return userMapper.insert(userEntity);
	}

	/**
     * 修改系统用户
     *
     * @param userEntity 系统用户信息
     * @return 结果
     */
	public int update(UserEntity userEntity) {
	    return userMapper.update(userEntity);
	}

	/**
	 * 删除用户对象
	 *
	 * @param id 系统ID
	 * @return 结果
	 */
	public int deleteById(Long id) {
		return userMapper.deleteById(id);
	}

	/**
	 * 用户登录
	 *
	 * @param authUserEntity 用户录入信息
	 */
	public TokenEntity login(AuthUserEntity authUserEntity) {
//		// 用户名
//		UsernamePasswordAuthenticationToken authenticationToken =
//				new UsernamePasswordAuthenticationToken(authUserEntity.getUsername(), authUserEntity.getPassword());
//		// 登录
//		//Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
//
//		//  登录
//		Authentication authentication = authenticationManager.authenticate(authenticationToken);
//		//  将用户信息保存到SecurityContextHolder中
//		SecurityContextHolder.getContext().setAuthentication(authentication);
//		// 生成token
//		String token = tokenHelper.generateToken((JwtUserEntity) (authentication.getPrincipal()));
//		//  返回token
//		return new TokenEntity(authUserEntity.getUsername(), token);
		String code = redisUtils.get(getCaptchaKey(authUserEntity.getUuid()));
		AssertUtil.hasLength(code,"该验证码不存在或者已失效");
		AssertUtil.isTrue(code.trim().equals(authUserEntity.getCode().trim()),"验证码错误");
		try{
			String decodePassword = passwordUtil.decodeRsaPassword(authUserEntity);
			UsernamePasswordAuthenticationToken authenticationToken= new UsernamePasswordAuthenticationToken(authUserEntity.getUsername(),decodePassword);
			Authentication authentication=authenticationManager.authenticate(authenticationToken);
			SecurityContextHolder.getContext().setAuthentication(authentication);
			String token=tokenHelper.generateToken((JwtUserEntity)(authentication.getPrincipal()));
			return new TokenEntity(authUserEntity.getUsername(),token);
		}catch(Exception e){
			redisUtils.del(getCaptchaKey(authUserEntity.getUuid()));
			log.info("登录失败：",e);
			throw new BusinessException(HttpStatus.FORBIDDEN.value(),"用户名或密码错误");
		}
	}

	/**
	 * 用户登出
	 *
	 * @param request 请求
	 */
	public void logout(HttpServletRequest request) {
		String token = TokenUtil.getTokenForAuthorization(request);
		AssertUtil.hasLength(token,"Authorization不正确");
		tokenHelper.delToken(token);
	}

    public CaptchaEntity getCode() {
		//生成验证码
		ArithmeticCaptcha captcha = new ArithmeticCaptcha(111,36);
  		//几位数运算，默认是两位
		captcha.setLen(2);
		//获取运算的结果
		String result="";
		try{
			result = new Double(Double.parseDouble(captcha.text())).intValue()+"";
		}catch(Exception e){
			result=captcha.text();
		}
		String uuid="C"+ IdUtil.simpleUUID();
		//保存验证码到Redis中
		redisUtils.set(getCaptchaKey(uuid),result,CAPTCHA_EXPIRE_SECOND);
		return new CaptchaEntity(uuid,captcha.toBase64());
    }

	private String getCaptchaKey(String uuid){
		return String.format("%s%s",CAPTCHA_PREFIX,uuid);
	}
}
